import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:dio/dio.dart';
import 'package:get/get.dart';
import '../services/index.dart';
import '../values/index.dart';

/// 网络诊断工具
/// 
/// 用于快速检测和诊断网络连接问题
class NetworkDiagnostics {
  static const String tag = 'NetworkDiagnostics';
  
  /// 完整网络诊断
  static Future<NetworkDiagnosticResult> runFullDiagnostics() async {
    debugPrint('🔍 $tag: 开始完整网络诊断...');
    
    final result = NetworkDiagnosticResult();
    
    try {
      // 1. 检查基础网络连接
      result.basicConnectivity = await _checkBasicConnectivity();
      debugPrint('✅ 基础网络连接: ${result.basicConnectivity}');
      
      // 2. 检查DNS解析
      result.dnsResolution = await _checkDNSResolution();
      debugPrint('✅ DNS解析: ${result.dnsResolution}');
      
      // 3. 检查API服务器连通性
      result.apiServerConnectivity = await _checkAPIServerConnectivity();
      debugPrint('✅ API服务器连通性: ${result.apiServerConnectivity}');
      
      // 4. 检查SSL证书
      result.sslCertificate = await _checkSSLCertificate();
      debugPrint('✅ SSL证书: ${result.sslCertificate}');
      
      // 5. 检查网络服务状态
      result.dioServiceStatus = await _checkDioServiceStatus();
      debugPrint('✅ Dio服务状态: ${result.dioServiceStatus}');
      
      result.overallStatus = _calculateOverallStatus(result);
      debugPrint('🎯 整体诊断结果: ${result.overallStatus}');
      
    } catch (e) {
      debugPrint('❌ $tag: 诊断过程出错: $e');
      result.overallStatus = NetworkStatus.error;
      result.errorMessage = e.toString();
    }
    
    return result;
  }
  
  /// 检查基础网络连接
  static Future<NetworkStatus> _checkBasicConnectivity() async {
    try {
      // 尝试连接Google DNS和百度DNS
      final futures = [
        InternetAddress.lookup(Constants.googleDns).timeout(Duration(seconds: 5)),
        InternetAddress.lookup(Constants.baiduDns).timeout(Duration(seconds: 5)),
      ];
      
      await Future.any(futures);
      return NetworkStatus.good;
      
    } catch (e) {
      debugPrint('❌ 基础网络连接失败: $e');
      return NetworkStatus.error;
    }
  }
  
  /// 检查DNS解析
  static Future<NetworkStatus> _checkDNSResolution() async {
    try {
      // 使用预定义的测试域名列表
      const testDomains = Constants.testDomains;
      
      int successCount = 0;
      
      for (final domain in testDomains) {
        try {
          await InternetAddress.lookup(domain).timeout(Duration(seconds: 3));
          successCount++;
          debugPrint('✅ DNS解析成功: $domain');
        } catch (e) {
          debugPrint('! DNS解析失败: $domain - $e');
        }
      }
      
      // 根据成功率评估DNS状态
      if (successCount >= 2) {
        return NetworkStatus.good;
      } else if (successCount >= 1) {
        return NetworkStatus.warning;
      } else {
        return NetworkStatus.error;
      }
      
    } catch (e) {
      debugPrint('❌ DNS解析检查失败: $e');
      return NetworkStatus.error;
    }
  }
  
  /// 检查API服务器连通性
  static Future<NetworkStatus> _checkAPIServerConnectivity() async {
    try {
      // 创建临时Dio实例进行测试
      final dio = Dio(BaseOptions(
        connectTimeout: Duration(milliseconds: Constants.defaultConnectTimeout),
        receiveTimeout: Duration(milliseconds: Constants.defaultReceiveTimeout),
        validateStatus: (status) => status != null && status < 600,
      ));
      
      // 使用常量中定义的API地址
      final testUrl = Constants.apiBaseUrl;
      
      // 尝试基础连接测试
      final response = await dio.get(
        testUrl,
        options: Options(headers: {'User-Agent': Constants.defaultUserAgent}),
      ).timeout(Duration(seconds: 10));
      
      // 任何响应都说明服务器可达
      if (response.statusCode != null) {
        debugPrint('✅ API服务器连接成功: ${response.statusCode}');
        return NetworkStatus.good;
      } else {
        return NetworkStatus.warning;
      }
      
    } catch (e) {
      debugPrint('❌ API服务器连接失败: $e');
      
      // 分析错误类型
      if (e is DioException) {
        switch (e.type) {
          case DioExceptionType.connectionTimeout:
          case DioExceptionType.receiveTimeout:
            return NetworkStatus.warning; // 超时可能是服务器慢
          case DioExceptionType.connectionError:
            return NetworkStatus.error;   // 连接错误是严重问题
          default:
            return NetworkStatus.warning; // 其他错误可能不严重
        }
      }
      
      return NetworkStatus.error;
    }
  }
  
  /// 检查SSL证书
  static Future<NetworkStatus> _checkSSLCertificate() async {
    try {
      // 从API基础URL中提取主机名和端口
      final uri = Uri.parse(Constants.apiBaseUrl);
      final host = uri.host;
      final port = uri.port != 0 ? uri.port : (uri.scheme == 'https' ? 443 : 80);
      
      final socket = await SecureSocket.connect(
        host, 
        port,
        timeout: Duration(seconds: 5),
      );
      
      final cert = socket.peerCertificate;
      socket.close();
      
      if (cert != null) {
        // 检查证书是否过期
        final now = DateTime.now();
        if (now.isAfter(cert.endValidity)) {
          debugPrint('⚠️ SSL证书已过期: ${cert.endValidity}');
          return NetworkStatus.warning;
        }
        
        debugPrint('✅ SSL证书有效，过期时间: ${cert.endValidity}');
        return NetworkStatus.good;
      } else {
        debugPrint('⚠️ 无法获取SSL证书');
        return NetworkStatus.warning;
      }
      
    } catch (e) {
      debugPrint('❌ SSL证书检查失败: $e');
      return NetworkStatus.error;
    }
  }
  
  /// 检查Dio服务状态
  static Future<NetworkStatus> _checkDioServiceStatus() async {
    try {
      if (Get.isRegistered<DioService>()) {
        final dioService = Get.find<DioService>();
        
        if (dioService.isInitialized && dioService.isOnline) {
          return NetworkStatus.good;
        } else if (dioService.isInitialized) {
          return NetworkStatus.warning;
        } else {
          return NetworkStatus.error;
        }
      } else {
        debugPrint('⚠️ DioService 未注册');
        return NetworkStatus.error;
      }
    } catch (e) {
      debugPrint('❌ Dio服务状态检查失败: $e');
      return NetworkStatus.error;
    }
  }
  
  /// 计算整体状态
  static NetworkStatus _calculateOverallStatus(NetworkDiagnosticResult result) {
    final statuses = [
      result.basicConnectivity,
      result.dnsResolution,
      result.apiServerConnectivity,
      result.sslCertificate,
      result.dioServiceStatus,
    ];
    
    // 如果有任何error，整体就是error
    if (statuses.contains(NetworkStatus.error)) {
      return NetworkStatus.error;
    }
    
    // 如果有warning，整体就是warning
    if (statuses.contains(NetworkStatus.warning)) {
      return NetworkStatus.warning;
    }
    
    // 全部good才是good
    return NetworkStatus.good;
  }
  
  /// 快速网络检测
  static Future<bool> quickNetworkCheck() async {
    try {
      await InternetAddress.lookup(Constants.googleDns).timeout(Duration(seconds: 3));
      return true;
    } catch (e) {
      debugPrint('❌ 快速网络检测失败: $e');
      return false;
    }
  }
  
  /// 生成诊断报告
  static String generateDiagnosticReport(NetworkDiagnosticResult result) {
    final buffer = StringBuffer();
    
    buffer.writeln('📊 网络诊断报告');
    buffer.writeln('==================');
    buffer.writeln('🕒 诊断时间: ${DateTime.now().toString()}');
    buffer.writeln('📱 整体状态: ${_getStatusText(result.overallStatus)}');
    buffer.writeln('');
    
    buffer.writeln('📋 详细检查结果:');
    buffer.writeln('• 基础网络连接: ${_getStatusText(result.basicConnectivity)}');
    buffer.writeln('• DNS解析能力: ${_getStatusText(result.dnsResolution)}');
    buffer.writeln('• API服务器连通: ${_getStatusText(result.apiServerConnectivity)}');
    buffer.writeln('• SSL证书状态: ${_getStatusText(result.sslCertificate)}');
    buffer.writeln('• Dio服务状态: ${_getStatusText(result.dioServiceStatus)}');
    
    if (result.errorMessage?.isNotEmpty == true) {
      buffer.writeln('');
      buffer.writeln('❌ 错误信息:');
      buffer.writeln(result.errorMessage);
    }
    
    buffer.writeln('');
    buffer.writeln(_generateSuggestions(result));
    
    return buffer.toString();
  }
  
  /// 生成建议
  static String _generateSuggestions(NetworkDiagnosticResult result) {
    final buffer = StringBuffer();
    buffer.writeln('💡 建议操作:');
    
    if (result.basicConnectivity == NetworkStatus.error) {
      buffer.writeln('• 检查WiFi/移动网络连接');
      buffer.writeln('• 尝试切换网络环境');
    }
    
    if (result.dnsResolution == NetworkStatus.error) {
      buffer.writeln('• 尝试更换DNS服务器');
      buffer.writeln('• 检查网络运营商DNS设置');
    }
    
    if (result.apiServerConnectivity == NetworkStatus.error) {
      buffer.writeln('• 检查防火墙设置');
      buffer.writeln('• 联系网络管理员');
      buffer.writeln('• 确认服务器地址正确');
    }
    
    if (result.sslCertificate == NetworkStatus.error) {
      buffer.writeln('• 检查设备系统时间');
      buffer.writeln('• 更新系统证书');
      buffer.writeln('• 联系技术支持检查服务器证书配置');
    }
    
    if (result.dioServiceStatus == NetworkStatus.error) {
      buffer.writeln('• 重启应用');
      buffer.writeln('• 清理应用缓存');
    }
    
    return buffer.toString();
  }
  
  /// 获取状态文本
  static String _getStatusText(NetworkStatus status) {
    switch (status) {
      case NetworkStatus.good:
        return '✅ 正常';
      case NetworkStatus.warning:
        return '⚠️ 警告';
      case NetworkStatus.error:
        return '❌ 错误';
    }
  }
}

/// 网络状态枚举
enum NetworkStatus {
  good,    // 正常
  warning, // 警告
  error,   // 错误
}

/// 网络诊断结果
class NetworkDiagnosticResult {
  NetworkStatus overallStatus = NetworkStatus.error;
  NetworkStatus basicConnectivity = NetworkStatus.error;
  NetworkStatus dnsResolution = NetworkStatus.error;
  NetworkStatus apiServerConnectivity = NetworkStatus.error;
  NetworkStatus sslCertificate = NetworkStatus.error;
  NetworkStatus dioServiceStatus = NetworkStatus.error;
  String? errorMessage;
  
  /// 是否网络健康
  bool get isHealthy => overallStatus == NetworkStatus.good;
  
  /// 是否有问题
  bool get hasIssues => overallStatus != NetworkStatus.good;
  
  @override
  String toString() {
    return 'NetworkDiagnosticResult{overallStatus: $overallStatus, isHealthy: $isHealthy}';
  }
}
